package xyz.xuetu.www.rpc.proxy;

import cn.hutool.core.collection.CollUtil;
import xyz.xuetu.www.rpc.RpcApplication;
import xyz.xuetu.www.rpc.config.RpcConfig;
import xyz.xuetu.www.rpc.constant.RpcConstant;
import xyz.xuetu.www.rpc.fault.retry.RetryStrategy;
import xyz.xuetu.www.rpc.fault.retry.RetryStrategyFactory;
import xyz.xuetu.www.rpc.fault.tolerant.TolerantStrategy;
import xyz.xuetu.www.rpc.fault.tolerant.TolerantStrategyFactory;
import xyz.xuetu.www.rpc.loadbalancer.LoadBalancer;
import xyz.xuetu.www.rpc.loadbalancer.LoadBalancerFactory;
import xyz.xuetu.www.rpc.model.RpcRequest;
import xyz.xuetu.www.rpc.model.RpcResponse;
import xyz.xuetu.www.rpc.model.ServiceMetaInfo;
import xyz.xuetu.www.rpc.registry.Registry;
import xyz.xuetu.www.rpc.registry.RegistryFactory;
import xyz.xuetu.www.rpc.server.tcp.VertxTcpClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态代理(JDK)
 */
public class ServiceProxy implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 构造请求
        String serviceName = method.getDeclaringClass().getName();
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(serviceName)
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .args(args)
                .build();
        // 从注册中心获取服务提供者请求地址
        RpcConfig rpcConfig = RpcApplication.getRpcConfig();
        Registry registry = RegistryFactory.getInstance(rpcConfig.getRegistryConfig().getRegistry());
        ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
        serviceMetaInfo.setServiceName(serviceName);
        serviceMetaInfo.setServiceVersion(RpcConstant.DEFAULT_SERVICE_VERSION);
        // 获取服务地址列表
        List<ServiceMetaInfo> serviceMetaInfoList = registry.serviceDiscovery(serviceMetaInfo.getServiceKey());
        if(CollUtil.isEmpty(serviceMetaInfoList)) {
            throw new RuntimeException("暂无服务地址");
        }
        // 负载均衡
        LoadBalancer loadBalancer = LoadBalancerFactory.getInstance(rpcConfig.getLoadBalancer());
        // 将调用方法名(请求路径)作为负载均衡参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("methodName", rpcRequest.getMethodName());
        ServiceMetaInfo selectServiceMetaInfo = loadBalancer.select(requestParams, serviceMetaInfoList);
        RpcResponse rpcResponse = null;
        try{
            // 使用重试策略
            RetryStrategy retryStrategy = RetryStrategyFactory.getInstance(rpcConfig.getRetryStrategy());
            rpcResponse = retryStrategy.doRetry(() -> {
                // throw new RuntimeException("模拟重试失败");
                // 发送 TCP 请求
                return VertxTcpClient.doRequest(rpcRequest, selectServiceMetaInfo);
            });
        }catch (Exception e) {
            // 容错机制
            TolerantStrategy tolerantStrategy = TolerantStrategyFactory.getInstance(rpcConfig.getTolerantStrategy());
            rpcResponse = tolerantStrategy.doTolerant(null, e);
        }
        return rpcResponse.getData();
    }
}
